
import { List, Button, Popconfirm } from 'antd';
import { PlusOutlined, MinusOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import React from 'react';
import { ICartProduct, ICartTotal, totalCartProduct } from "../../models";
import formatPrice from 'utils/formatPrice';
import { CartLocalStorage } from 'local/CartLocalStorage';

const totalCurrencyId = 'USD';
const totalCurrencyFormat = '$';

interface IProps {
    openTS: number;
    onCheckout: (products: ICartProduct[], total: ICartTotal) => void;
}
interface IState {
    list: ICartProduct[];
}

export class Cart extends React.Component<IProps, IState> {
    constructor(props: any) {
        super(props);
        this.state = {
            list: [],
        };
    }

    loadList() {
        const ret = CartLocalStorage.loadProducts();
        if (!ret.success) {
            console.error('购物车加载本地数据失败', ret, '将使用全空购物车开始');
            this.setState({
                list: [],
            });
        } else {
            this.setState({
                list: ret.data,
            });
        }
    }

    componentDidMount(): void {
        this.loadList();
    }

    componentDidUpdate(prevProps: IProps): void {
        if (prevProps.openTS === this.props.openTS) return;
        this.loadList();
    }

    onIncrease(product: ICartProduct) {
        let cp = this.state.list.find(p => p.key === product.key);
        if (!cp) {
            return console.error('onIncrease no match', product);
        }
        cp.quantity += 1;
        CartLocalStorage.saveProducts(this.state.list);
        this.setState({
            list: this.state.list,
        });
    }
    onDecrease(product: ICartProduct) {
        let cp = this.state.list.find(p => p.key === product.key);
        if (!cp) {
            return console.error('onDecrease no match', product);
        }
        cp.quantity -= 1;
        CartLocalStorage.saveProducts(this.state.list);
        this.setState({
            list: this.state.list,
        });
    }
    onRemove(product: ICartProduct) {
        let cpIndex = this.state.list.findIndex(p => p.key === product.key);
        if (cpIndex < 0) {
            return console.error('onRemove no match', product);
        }
        this.state.list.splice(cpIndex, 1);
        CartLocalStorage.saveProducts(this.state.list);
        this.setState({
            list: this.state.list,
        });
    }

    onCheckout(total: ICartTotal) {
        this.props.onCheckout(this.state.list, total);
    }


    render() {
        const total = totalCartProduct(this.state.list, totalCurrencyId);
        const totalPriceFormat = formatPrice(total.totalPrice, totalCurrencyId);
        const totalInstallmentsPrice = total.minInstallments ? formatPrice(total.totalPrice / total.minInstallments, totalCurrencyId) : null;
        return (
            <div className='cartWrap'>
                <List
                    className='cartList'
                    itemLayout="horizontal"
                    dataSource={this.state.list}
                    renderItem={item => (
                        <List.Item
                            className='cartItem'
                            actions={[
                                <div>{item.currencyFormat} {formatPrice(item.price, item.currencyId)}</div>,
                                <Button className='cartItemCountCtl' disabled={item.quantity <= 1}
                                    onClick={() => this.onDecrease(item)}><MinusOutlined /></Button>,
                                <div className="cartItemQuantity">{item.quantity}</div>,
                                <Button className='cartItemCountCtl'
                                    onClick={() => this.onIncrease(item)}><PlusOutlined /></Button>,
                                <Button className='cartItemCountCtl'
                                    onClick={() => this.onRemove(item)}><DeleteOutlined /></Button>
                            ]}
                        >
                            <List.Item.Meta
                                avatar={(
                                    <div className='cartItemImg'><img alt={item.title} src={require(`static/products/${item.sku}-1-cart.webp`)} /></div>
                                )}
                                title={item.title}
                                description={(
                                    <div>
                                        <div>{item.selectedOptions.selectedSize} | {item.style}</div>
                                    </div>
                                )}
                            />
                        </List.Item>
                    )
                    }
                />
                {total.count > 0 && (
                    <div className='cartFoot'>
                        <div className='cartFootCalcWrap'>
                            <div>SUBTOTAL</div>
                            <div className='cartFootCalcP'>
                                <div className='cartFootCalcPrice'>{totalCurrencyFormat} {totalPriceFormat}</div>
                                {total.minInstallments ? (
                                    <div className='cartFootCalcDesc'>OR UP TO {total.minInstallments} x
                                        {totalCurrencyFormat} {totalInstallmentsPrice}</div>
                                ) : null}
                            </div>
                        </div>
                        <div className='cartFootCheckout'>
                            <Popconfirm title={`共件商品${total.count}，总价为${totalCurrencyFormat} ${totalPriceFormat}，确认提交订单？`}
                                icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                                onConfirm={() => this.onCheckout(total)}>
                                <Button>Checkout</Button>
                            </Popconfirm>
                        </div>
                    </div>
                )}
            </div>
        );
    }
}

export default Cart;
